package com.landmesure.settings.fragment;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatSpinner;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.code.ValueType;
import com.landmesure.bluetoothchat.R;
import com.landmesure.settings.SettingActivity;
import com.landmesure.settings.fragment.argsinfo.ArgumentsInfo;
import com.landmesure.settings.fragment.argsinfo.DataHelper;
import com.landmesure.settings.fragment.tree.TypeTreeNote;
import com.widget.CustomWidget;
import com.widget.SelectCallBack;

import java.util.ArrayList;

public class ArgumentsFragment extends Fragment implements TypeFragment.ArgumentsCallBack {
    private static final String TAG = "ArgumentsFragment";

    private ArrayList<ArgumentsInfo> mArgumentsInfos = new ArrayList<>();    //参数集合
    private Context mContext;
    private DataHelper mDataHelper;    //DataHelper实例,与TypeFragment中的相同
    private ArrayList<String> mArgValues = new ArrayList<>();    //设置参数的参数编码集合
    private TypeTreeNote mNote;    //设置参数所选的对象
    private CustomWidget mCustomWidget;    //自定义控件;

    private int mNoteIndex = 0;
    private int mSelection = -1;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        Log.i(TAG, "onCreate");
        super.onCreate(savedInstanceState);

        mContext = getActivity();
        mCustomWidget = new CustomWidget(mContext);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             Bundle savedInstanceState) {
        Log.i(TAG, "onCreateView");

        View viewFragment = inflater.inflate(R.layout.layout_arguments_fragment,
                container, false);
        TableLayout tableLayout = viewFragment.findViewById(R.id.arguments_info_form);
        createRows(mArgumentsInfos, inflater, tableLayout);
        return viewFragment;
    }

    /**
     * 创建参数表格
     */
    private void createRows(ArrayList<ArgumentsInfo> argumentsInfos,
                            LayoutInflater inflater, TableLayout tl) {
        if (null == argumentsInfos || argumentsInfos.isEmpty()) {
            return;
        }
        int i = 0;
        for (ArgumentsInfo info : argumentsInfos) {
            inflater.inflate(R.layout.tablerow_arguments_info,
                    tl, true);
            View view = tl.getChildAt(i);
            View[] textViews = initChild(view);
            ((TextView) textViews[0]).setText(String.valueOf(i + 1));
            ((TextView) textViews[1]).setText(info.mPropName);
            if (info.mIsSelect) {
                ((LinearLayout) textViews[2]).addView(createSpinner(inflater, info));
            } else {
                ((LinearLayout) textViews[2]).addView(createTextView(info));
            }
            if (!TextUtils.isEmpty(info.mUnits)) {
                ((TextView) textViews[3]).setText(info.mUnits);
            }
            ((TextView) textViews[4]).setText(info.mArguType);
            ((TextView) textViews[5]).setText(info.mArguValue);
            view.clearFocus();
            i++;
        }
    }

    /**
     * 初始化子视图
     */
    private View[] initChild(View view) {
        View[] views = new View[6];
        views[0] = view.findViewById(R.id.tv_line_number);
        views[1] = view.findViewById(R.id.tv_prop_name);
        views[2] = view.findViewById(R.id.tv_prop_value);
        views[3] = view.findViewById(R.id.tv_units);
        views[4] = view.findViewById(R.id.tv_argu_tpe);
        views[5] = view.findViewById(R.id.tv_argu_value);
        return views;
    }

    /**
     * 编辑框
     */
    @SuppressLint("ClickableViewAccessibility")
    private View createTextView(final ArgumentsInfo info) {
        final EditText editText = new EditText(mContext);
        if (info.mIsEditable) {
            editText.setEnabled(true);
            if (ValueType.TIME.equals(info.mPropType) || ValueType.DATETIME.equals(info.mPropType)) {
                editText.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (MotionEvent.ACTION_DOWN == event.getAction()) {
                            if (ValueType.TIME.equals(info.mPropType)) {
                                setTime(editText);
                                return true;
                            } else if (ValueType.DATETIME.equals(info.mPropType)) {
                                setDate(editText);
                                return true;
                            }
                        }
                        return false;
                    }
                });
            }
        } else {
            editText.setEnabled(false);
        }
        editText.setMaxLines(2);
        editText.setText(info.mPropValue);
        editText.setTextSize(15);
        editText.setTextColor(Color.GRAY);
        editText.setGravity(Gravity.CENTER);

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!mArgValues.contains(info.mArguValue)) {
                    mArgValues.add(info.mArguValue);
                } else if (info.mPropValue.equals(s.toString())) {
                    mArgValues.remove(info.mArguValue);
                }
                if (mArgValues.contains(info.mArguValue)) {
                    info.mPropValue = s.toString();
                }
            }

            @Override
            public void afterTextChanged(Editable s) { }
        });
        return editText;
    }

    /**
     * 时间控件
     */
    private void setTime(final EditText et) {
        mCustomWidget.timeWidget(et);
    }

    /**
     * 日期控件
     */
    private void setDate(final EditText et) {
        mCustomWidget.dateWidget(et);
    }

    /**
     * 下拉控件
     */
    private View createSpinner(LayoutInflater inflater, final ArgumentsInfo info) {
        ArrayList<String> selects = info.mSelects;
        if (null == selects || selects.isEmpty()) {
            Log.e(TAG, "spinner list error");
            return null;
        }
        int selection = -1;
        if (selects.contains(info.mSelectStr)) {
            selection = selects.indexOf(info.mSelectStr);
        }

        AppCompatSpinner spinner = mCustomWidget.spinnerWidget(inflater, selects, selection);
        spinner.setSelection(selection, true);
        final SelectCallBack callBack = mCustomWidget.getAdapter();
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position != mSelection) {
                    mSelection = position;
                    info.mSelectStr = (String) parent.getItemAtPosition(position);
                    if (!mArgValues.contains(info.mArguValue)) {
                        mArgValues.add(info.mArguValue);
                    }
                } else if (mArgValues.contains(info.mArguValue)) {
                    mArgValues.remove(info.mArguValue);
                }
                callBack.setSelectItem(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) { }
        });
        return spinner;
    }

    /**
     * 设置参数
     */
    public void setEntityType() {
        if (null == mDataHelper || null == mNote) {
            Log.e(TAG, "setEntityType, pointer is null");
            return;
        }
        if (null == mArgValues || mArgValues.isEmpty()) {
            Log.i(TAG, "not any property changed");
            Toast.makeText(mContext, "未检测到参数改变，无需设置", Toast.LENGTH_SHORT).show();
            return;
        }
        mDataHelper.setEntityType(mNote, mArgValues);
        mArgValues.clear();
        mSelection = -1;
    }

    /**
     * 选测
     */
    public void choiceTest() {
        if (null == mDataHelper) {
            Log.e(TAG, "choiceTest, mDataHelper is null");
            return;
        }
        mDataHelper.choiceTest(mNoteIndex);
    }

    /**
     * 查询参数
     */
    public void queryArgs() {
        if (null == mDataHelper) {
            Log.e(TAG, "queryArgs, mDataHelper is null");
            return;
        }
        mDataHelper.queryArgs();
    }

    /**
     * 复位
     */
    public void reset() {
        if (null == mDataHelper) {
            Log.e(TAG, "queryArgs, mDataHelper is null");
            return;
        }
        mDataHelper.reset();
    }

    @Override
    public void setArguments(ArrayList<ArgumentsInfo> infoArrayList) {
        mArgumentsInfos = infoArrayList;
        ((SettingActivity) mContext).updateFragment(this);
    }

    @Override
    public void setArgumentsInit(ArrayList<ArgumentsInfo> infoArrayList) {
        mArgumentsInfos = infoArrayList;
    }

    @Override
    public void setDataHelperInstance(DataHelper dataHelper) {
        mDataHelper = dataHelper;
    }

    @Override
    public void setSelectNote(TypeTreeNote note, int index) {
        mNote = note;
        mNoteIndex = index;
    }
}